#!/usr/bin/env php
<?php
// -----------------------------------------------------------------------------
// sdefastsearch - A PHP Fast ESP Search API
// Copyright (C) 2008,2009 sueddeutsche.de GmbH, Hultschiner Str. 8, D-81677 München
// www.sueddeutsche.de.de - Andreas.Scheerer@sueddeutsche.de
//
// This file is part of sdefastsearch.
//
// sdefastsearch is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------

/**
 * Cli example using navigation concept.
 * 
 * @author  Andreas Scheerer <Andreas.Scheerer@sueddeutsche.de
 * @version $Id$ 
 */

//--------------------------------------------------------------------------
//---                               config                               ---
//-------------------------------------------------------------------------- 
set_include_path(dirname(__FILE__).'/../../src/');

//--------------------------------------------------------------------------
//---                               includes                             ---
//-------------------------------------------------------------------------- 
require_once 'sde/fastsearch/SearchFactory.php';
require_once 'sde/fastsearch/query/Query.php';
require_once 'sde/fastsearch/navigation/Navigation.php';

//--------------------------------------------------------------------------
//---                                 main                               ---
//-------------------------------------------------------------------------- 

// Params
// remove script name
array_shift($argv);
if (count($argv) < 2) {
    showInfo();
    exit();
}

$host     = $argv[0];
$port     = $argv[1];
$query    = "";
$viewName = "";

if (count($argv) > 2)
   $viewName = $argv[2];

// Properties
$properties = array (
    'fastsearch.SearchFactory' => "http.HttpSearchFactory",
    'fastsearch.http.qservers' => "$host:$port"
    );

try {
    // Get searchfactory
    $searchFactory = SearchFactory::newInstance($properties);

    // Printing list of views.
    if (empty($viewName)) {
        $list = $searchFactory->getSearchViewList();
    
        print "Views located at $host:$port\n";
    
        if (count($list) > 0) {
            for ($i = 0; $i < count($list); $i++) 
                print $list[$i]."\n";
        } else {
            print "No views found.\n";
        }
        exit();
    }

    // Get view.
    $view = $searchFactory->getSearchView($viewName);
    
    // Create the query and do a search.              
    for ($i = 3; $i < count($argv); $i++) {
        if (substr(trim($argv[$i]),0,1) == '-' ) continue; 
        $query .= $argv[$i];
        $query .= " ";
    }
    
    $query = str_replace('"', '\"', $query);
    $query = 'string("'.trim($query).'")';
    
    $firstQuery = new Query();
    $firstQuery->setQueryString($query);
    
    // enable navigation
    $param = new SearchParameter(BaseParameter::NAVIGATION,1);
    $firstQuery->setParameter($param);

    print "Query string: " . $firstQuery->getQueryString($firstQuery) . "\n\n";

    $firstResult = $view->search($firstQuery);

    if ($firstResult->navigatorCount() == 0) {
        print "There are no navigators in the search result\n"; 
        exit();
    }

    // Print out each navigator with its data
    print "FIRST SEARCH RESULT\n===================\n";
    print "(".$firstResult->getDocCount()." documents)\n\n";
    print "Request-URL: ".$firstResult->getHttpSearchURL()."\n\n";
    print "The result contains the navigators listed below with data as shown on next line\n";
    print "[ (name), (hits), (unit), (min), (max), (mean) ] \n";  
    $lastNavigator = null;

    $navIterator = $firstResult->navigators();

    while($navIterator->valid()) {
        $navigator = $navIterator->current();
        print "[";
        print " (" . $navigator->getDisplayName() . "),";  
        print " (" . $navigator->getHits() . "),";  
        print " (" . $navigator->getUnit() . "),"; 
        print " (" . $navigator->getMin() . "),"; 
        print " (" . $navigator->getMax() . "),"; 
        print " (" . $navigator->getMean() . ")"; 
        print "]\n"; 
      
        $navIterator->next();
        if ($navigator->modifierCount() > 1 
            || ($lastNavigator==null && !$navIterator->valid())) {
            $lastNavigator = $navigator;
        }     
    }
    
    // Print out the modifer for the last navigator from above
    print "\n\nNavigator '" . $lastNavigator->getDisplayName() . "' has the modifiers ";
    print "listed below (data as on the next line)\n";
    print "[ (modifier name), (hits), (actual query value), (document ratio) ] \n";
    
    $lastModifier = null;
    $modIterator = $lastNavigator->modifiers();

    while ($modIterator->valid()) {
        $modifier = $modIterator->current();  
        print "[";
        print " (" . $modifier->getName() . "),";  
        print " (" . $modifier->getCount() . "),";
        print " (" . $modifier->getValue() . "),"; 
        print " (" . $modifier->getDocumentRatio() . ")"; 
        print "]\n"; 
        $lastModifier = $modifier;
        $modIterator->next();
    }
    
    // Create an navigation object. Use it to create an "adjustment" 
    // (to previous query) based on navigators and modifiers.
    $navigation = new Navigation();
    $adjustmentGroup = $navigation->add($lastNavigator);
    $adjustment = $adjustmentGroup->add($lastModifier);
    
    // Use the navigation object to create a new (adjusted) query
    $drillDownQuery = new Query($firstQuery);
    $navigation->instrument($drillDownQuery);
    
    $drillDownResult = $view->search($drillDownQuery);
    
    // Dump the new drill downed search result to the terminal window
    print "\nSEARCH RESULT AFTER DRILL DOWN\n==============================\n";
    print "(".$drillDownResult->getDocCount()." documents)\n\n";
    print "Request-URL: ".$drillDownResult->getHttpSearchURL()."\n\n";
    $documentIterator = $drillDownResult->documents();
        
    while ($documentIterator->valid()) {
        $documentSummary = $documentIterator->current();
        print "-------- DocNo #".$documentSummary->getDocNo()." --------\n";
        print "[collection] "
            .$documentSummary->getSummaryFieldByName('collection')->getStringValue()."\n";
        print "[title] "
            .$documentSummary->getSummaryFieldByName('title')->getStringValue()."\n";
        print "[body] "
            .$documentSummary->getSummaryFieldByName('body')->getStringValue()."\n\n";
        $documentIterator->next();
    }
    
    // Exit
    print "Execution complete.\n";

} catch (ConfigurationException $e) {
    print "CONFIG_ERROR: ".$e->getMessage()."\n\nException trace:\n";
    print $e->getTraceAsString();
    exit(1);
} catch (Exception $e) {
    print "ERROR: ".$e->getMessage()."\n\nException trace:\n";
    print $e->getTraceAsString();
    exit(1);
}


//--------------------------------------------------------------------------
//---                             functions                              ---
//-------------------------------------------------------------------------- 
function showInfo() {
    print "usage: navSearch.php <host> <port> [view] [one or more query terms]\n";
    print "If no view and query term(s) are given, a list of avaible views will be shown.\n";
    print "example: navSearch.php localhost 15100 myview George Washington\n";
}
